{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 字符串基础操作题\n",
    " \n",
    "假设有一个初始字符串 `s = \"Hello, Python world!\"`，进行下面的操作："
   ],
   "id": "54d63d6fe09c1a53"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T05:32:57.255241Z",
     "start_time": "2024-11-20T05:32:57.234059Z"
    }
   },
   "cell_type": "code",
   "source": [
    "s = \"Hello, Python world!\"\n",
    "# 1. 字符串长度计算\n",
    "print(len(s))\n",
    "# 2. 计算字符串中\"o\"字符的个数\n",
    "print(s.count('o'))\n",
    "# 3. 将字符串转换为大写\n",
    "print(s.upper())\n",
    "# 4. 将字符串转换为小写\n",
    "print(s.lower())\n",
    "# 5. 查找\"Python\"在字符串中的位置\n",
    "print(s.find('Python'))"
   ],
   "id": "3367473c63a0ea93",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n",
      "3\n",
      "HELLO, PYTHON WORLD!\n",
      "hello, python world!\n",
      "7\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T05:35:27.388522Z",
     "start_time": "2024-11-20T05:35:27.367181Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 6. 替换字符串中的\"world\"为\"universe\"\n",
    "print(s.replace('world', 'universe'))\n",
    "# 7. 检查字符串是否以\"Hello\"开始\n",
    "print(s.startswith('Hello'))\n",
    "# 8. 检查字符串是否以\"!\"结尾\n",
    "print(s.endswith('!'))\n",
    "# 9. 以\",\"为分隔符，拆分字符串\n",
    "print(s.split(','))\n",
    "# 10. 去除字符串首尾的\"!\"\n",
    "print(s.rstrip('!'))"
   ],
   "id": "86036844017c7a42",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Python universe!\n",
      "True\n",
      "True\n",
      "['Hello', ' Python world!']\n",
      "Hello, Python world\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T05:48:29.365202Z",
     "start_time": "2024-11-20T05:48:29.354209Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 11. 字符串反转\n",
    "print(''.join(reversed(s))) # 接收一个序列（比如字符串、列表或元组）作为参数，并返回一个逆序的迭代器。\n",
    "print(s[::-1])\n",
    "# 12. 字符串切片，获取\"Python\"\n",
    "print(s[7:13])\n",
    "# 13. 将字符串s中的\"Hello,\"删除\n",
    "print(s.replace('Hello','')) # 删除子串：将子串替换为空\n",
    "# 14. 拼接两个字符串 \"Hello,\" 和 \"World!\"\n",
    "print(\"Hello,\" +\"World!\")\n",
    "# 15. 使用f-string合并字符串和数字2021\n",
    "print('{} {}'.format(s,2021))"
   ],
   "id": "252e45502c4161dd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "!dlrow nohtyP ,olleH\n",
      "!dlrow nohtyP ,olleH\n",
      "Python\n",
      ", Python world!\n",
      "Hello,World!\n",
      "Hello, Python world! 2021\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T05:55:40.386124Z",
     "start_time": "2024-11-20T05:55:40.369120Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 16. 找出'a'第一次出现的位置\n",
    "print(s.find('a'))\n",
    "# 17. 找出'e'最后一次出现的位置\n",
    "print(s.rfind('e'))\n",
    "# 18. 计算字符串中空格的数量\n",
    "print(s.count(' '))\n",
    "# 19. 使用循环遍历字符串中的每个字符\n",
    "for i in s:\n",
    "    print(i)\n",
    "# 20. 将字符串转为\"列表\"形式，每个字符为一个列表元素\n",
    "print(list(s))"
   ],
   "id": "ffa96b94b8528c2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-1\n",
      "1\n",
      "2\n",
      "H\n",
      "e\n",
      "l\n",
      "l\n",
      "o\n",
      ",\n",
      " \n",
      "P\n",
      "y\n",
      "t\n",
      "h\n",
      "o\n",
      "n\n",
      " \n",
      "w\n",
      "o\n",
      "r\n",
      "l\n",
      "d\n",
      "!\n",
      "['H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'w', 'o', 'r', 'l', 'd', '!']\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T06:01:05.327755Z",
     "start_time": "2024-11-20T06:01:05.307755Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 21. 字符串排序（提示：先转换为列表）\n",
    "print(list(s).sort())\n",
    "# 22. 判断字符串是否为数字\n",
    "print(s.isnumeric())\n",
    "# 23. 将列表 `['Hello,', 'Python', 'World!']` 使用空格连接为一个字符串\n",
    "print(' '.join(['Hello,', 'Python', 'World!']))\n",
    "# 24. 使用%操作符格式化字符串，将数字100插入到\"Number: \"后面\n",
    "print('Number:%d'%100)\n",
    "# 25. 检查字符串是否全部为小写字母\n",
    "print(s.islower())"
   ],
   "id": "5ec42a9f8797488e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n",
      "False\n",
      "Hello, Python World!\n",
      "Number:100\n",
      "False\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T06:18:18.298769Z",
     "start_time": "2024-11-20T06:18:18.288766Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 26. 检查字符串是否全部为大写字母\n",
    "print(s.isupper())\n",
    "# 27. 将数字列表 `[1, 2, 3]` 转换成字符串，元素之间用`-`连接\n",
    "numbers=[1, 2, 3]\n",
    "print('-'.join(map(str, numbers))) # map()将列表中的每个数字转换为字符串\n",
    "# 28. 找出字符串中所有的\"o\"的位置\n",
    "print([index for index, char in enumerate(s) if char == \"o\"]) # enumerate(s) 会生成一个包含每个字符索引和字符本身的迭代器。\n",
    "# 29. 替换字符串中的第一个\"o\"为\"O\"\n",
    "print(s.replace('o','O',1))\n",
    "# 30. 字符串插入操作，向字符串指定位置插入子字符串\"amazing \"\n",
    "print(s[:-1]+\" amazing\"+s[-1:])"
   ],
   "id": "5dcd05383fd632be",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "1-2-3\n",
      "[4, 11, 15]\n",
      "HellO, Python world!\n",
      "Hello, Python world amazing!\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T06:19:11.421966Z",
     "start_time": "2024-11-20T06:19:11.404232Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 关于map()函数的使用：map() 函数在Python中是一个非常实用的内置函数，它允许你对一个序列的所有元素执行特定的操作。\n",
    "# 可以结合匿名函数\n",
    "numbers = [1, 2, 3, 4]\n",
    "result = map(lambda x: x * x, numbers)\n",
    "print(list(result)) "
   ],
   "id": "b445346c93079bfd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16]\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "进阶   \n",
    "给定字符串   \n",
    "s = \"Python is great!\""
   ],
   "id": "fd050a01e7b6bd1b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T06:34:07.910095Z",
     "start_time": "2024-11-20T06:34:07.892291Z"
    }
   },
   "cell_type": "code",
   "source": [
    "s = \"Python is great!\"\n",
    "# 1. 字符串反转: 给定字符串`s = \"Python is great!\"`，不使用任何内置函数，编写代码以反转字符串。\n",
    "print(s[::-1])\n",
    "# 2. 字符计数: 对于同一个字符串`s`，计算字符 `t'` 在其中出现的次数。\n",
    "print(s.count('t'))\n",
    "# 3. 替换字符: 把字符串`s` 中的所有空格替换成下划线 ``。\n",
    "print(s.replace(' ','-'))\n",
    "# 4. 检查回文: 检查字符串`s2 = \"A man, a plan, a canal, Panama!\"` 在忽略大小写、标点和空格的情况下是否为回文字符串。\n",
    "import re\n",
    "s2 = \"A man, a plan, a canal, Panama!\"\n",
    "s2_lower = s2.lower()\n",
    "s2_cleaned =re.sub(r'[,.! ]+','',s2_lower) # 正则表达式替换：逗号句号叹号空格\n",
    "print(s2_cleaned==s2_cleaned[::-1])\n",
    "# 5. 子字符串查找: 在`s` 中查找第一次出现子字符串 `is\"` 的位置。\n",
    "print(s.find('is'))\n"
   ],
   "id": "ef102ea669adc357",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "!taerg si nohtyP\n",
      "2\n",
      "Python-is-great!\n",
      "True\n",
      "7\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T06:46:26.000719Z",
     "start_time": "2024-11-20T06:46:25.978070Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 正则表达式\n",
    "# re模块提供了多种方法来执行正则表达式操作，包括：\n",
    "# re.match()：从字符串的开始位置匹配正则表达式，如果开头匹配，才会向下进行匹配。\n",
    "# re.search()：扫描整个字符串，返回第一个成功的匹配。\n",
    "# re.findall()：找出字符串中所有匹配正则表达式的子串。\n",
    "# re.sub()：替换字符串中匹配正则表达式的部分。\n",
    "# re.split()：根据匹配正则表达式的部分来分割字符串。\n"
   ],
   "id": "a75104ed49dc8683",
   "outputs": [],
   "execution_count": 29
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T07:15:18.554871Z",
     "start_time": "2024-11-20T07:15:18.533871Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 6. 字符串插入: 在`s` 中第一个 `t'` 字符之后插入子字符串`\"_inserted\"`。\n",
    "index_char=s.index('t')\n",
    "print(s[:index_char+1]+'_inserted'+s[index_char+1:])\n",
    "# 7. 部分替换: 替换`s` 中第一次出现的 `great\"` 为 `awesome\"`。\n",
    "print(s.replace('great','awesome',1))\n",
    "# 8. 切片与拼接: 将`s` 切分为两部分，其中第一部分包含前半部分的字符，第二部分包含后半部分的字符，然后将这两部分以相反顺序拼接起来。\n",
    "print(s[5:]+s[:5])\n",
    "# 9. 创建字符串列表: 使用列表生成式，根据字符串`s` 创建一个列表，其中包含`s` 的每个单词的首字母大写形式。\n",
    "ls=list(s.split(' '))\n",
    "res=[]\n",
    "for i,sub in enumerate(ls):\n",
    "    if sub.count('s'):\n",
    "        ls[i]=sub.capitalize() # 字符串首字母大写其余小写\n",
    "print(ls)\n",
    "# 10. 字符替换加密: 编写一个函数`encrypt`，使用字典 `a: m, b: n, ... z: l}` 的对应规则加密字符串`s3 = \"encryption\"`。\n",
    "# 创建加密字典\n",
    "# ord() 函数将字符转换为对应的ASCII码，chr() 函数用于将一个整数（ASCII码）转换为对应的字符。\n",
    "encryption_dict = {chr(i): chr((i - ord('a') + 13) % 26 + ord('a')) for i in range(ord('a'), ord('z') + 1)}\n",
    "# 对26取余\n",
    "# 打印字典\n",
    "print(encryption_dict)\n",
    "s3 = \"encryption\"\n",
    "res=''\n",
    "for i in s3:\n",
    "    res+=encryption_dict[i]\n",
    "print(res)"
   ],
   "id": "79e76cbc28ea681f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pyt_insertedhon is great!\n",
      "Python is awesome!\n",
      "n is great!Pytho\n",
      "['Python', 'Is', 'great!']\n",
      "{'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q', 'e': 'r', 'f': 's', 'g': 't', 'h': 'u', 'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y', 'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c', 'q': 'd', 'r': 'e', 's': 'f', 't': 'g', 'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k', 'y': 'l', 'z': 'm'}\n",
      "rapelcgvba\n"
     ]
    }
   ],
   "execution_count": 39
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 列表练习题\n",
    "初始\n"
   ],
   "id": "5d01017fe302dc6a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T07:37:28.150801Z",
     "start_time": "2024-11-20T07:37:28.138047Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1. 创建一个列表`list1`，其包含元素 1, 2, 3, 4, 5。\n",
    "list1=[1, 2, 3, 4, 5]\n",
    "print(list1)\n",
    "# 2. 向`list1` 添加一个元素 6。\n",
    "list1.append(6)\n",
    "print(list1)\n",
    "# 3. 从`list1` 中删除元素 3。\n",
    "list1.remove(3)\n",
    "print(list1)\n",
    "# 4. 修改`list1` 中的第二个元素值为 8。\n",
    "list1[1]=8\n",
    "print(list1)\n",
    "# 5. 找出`list1` 中值为 8 的元素索引。\n",
    "print(list1.index(8))\n",
    "# 6. 遍历`list1`，打印每个元素的值。\n",
    "for i in list1:\n",
    "    print(i)\n",
    "# 7. 利用循环，将一个新列表 `7, 8, 9]` 的每个元素添加到`list1` 的末尾。\n",
    "for i in [7, 8, 9]:\n",
    "    list1.append(i)\n",
    "# 8. 使用一个命令，将列表 `10, 11, 12]` 添加到`list1` 的末尾。\n",
    "print(list1+[10, 11, 12])\n",
    "# 9. 使用切片操作，获取`list1` 第三个元素到第五个元素（包含第五个元素）。\n",
    "print(list1[2:5])\n",
    "# 10. 将`list1` 的第三个元素修改为两个新元素 `13, 14]`（不是列表中的一个列表，而是将两个新元素插入到指定位置）。\n",
    "print(list1[:2]+[13,14]+list1[3:])"
   ],
   "id": "e9d61993068e1b8d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5]\n",
      "[1, 2, 3, 4, 5, 6]\n",
      "[1, 2, 4, 5, 6]\n",
      "[1, 8, 4, 5, 6]\n",
      "1\n",
      "1\n",
      "8\n",
      "4\n",
      "5\n",
      "6\n",
      "[1, 8, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n",
      "[4, 5, 6]\n",
      "[1, 8, 13, 14, 5, 6, 7, 8, 9]\n"
     ]
    }
   ],
   "execution_count": 46
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T08:08:52.923478Z",
     "start_time": "2024-11-20T08:08:52.907465Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 给定初始列表`my_list = [3, \"apple\", 9, \"banana\", 7, \"cherry\", 2, \"date\", 5, \"elderberry\"]`，执行以下操作：\n",
    "my_list = [3, \"apple\", 9, \"banana\", 7, \"cherry\", 2, \"date\", 5, \"elderberry\"]\n",
    "# 1. 向my_list中添加一个元素\"fig\"。\n",
    "my_list.append(\"fig\")\n",
    "print(my_list)\n",
    "# 2. 从my_list中删除元素\"banana\"。\n",
    "my_list.remove(\"banana\")\n",
    "print(my_list)\n",
    "# 3. 将元素7修改为字符串\"grape\"。\n",
    "my_list[6]=\"grape\"\n",
    "print(my_list)\n",
    "# 4. 查找并打印元素\"cherry\"的索引值。\n",
    "print(my_list.index(\"cherry\"))\n",
    "# 5. 遍历my_list并打印每个元素。\n",
    "for i in my_list:\n",
    "    print(i)\n",
    "# 6. 在\"cherry\"后面插入新元素\"kiwi\"。\n",
    "my_list.insert(my_list.index(\"cherry\")+1,\"kiwi\")\n",
    "print(my_list)\n",
    "# 7. 使用索引查找并打印第三个元素。\n",
    "print(my_list[2])\n",
    "# 8. 使用负数索引找到并打印倒数第二个元素。\n",
    "print(my_list[-2])\n",
    "# 9. 使用切片操作获取第三个至第七个元素并打印结果。\n",
    "print(my_list[2:7])\n",
    "# 10. 使用切片操作反转整个列表并打印结果。\n",
    "print(my_list[::-1])\n",
    "# 11. 对列表中的字符串进行排序，并保留数字在原位。\n",
    "# 提取字符串并排序\n",
    "print(my_list)\n",
    "sorted_strings=sorted([item for item in my_list if isinstance(item,str)]) # 列表生成式\n",
    "str_index=0\n",
    "for i in range(len(my_list)):\n",
    "    if isinstance(my_list[i],str):\n",
    "        my_list[i]=sorted_strings[str_index]\n",
    "        str_index+=1\n",
    "print(my_list)\n",
    "# 12. 将my_list中的数字替换为它们对应的字符串形式（如1->'one'），不改变列表中原有的字符串。\n",
    "dict1={1:\"one\",2:\"two\",3:\"three\",4:\"four\",5:\"five\",6:\"six\",7:\"seven\",8:\"eight\",9:\"nine\"}\n",
    "list2=[]\n",
    "for i in my_list:\n",
    "    if str(i).isnumeric():\n",
    "        i=dict1[i]\n",
    "    list2.append(i)\n",
    "print(list2)\n",
    "    "
   ],
   "id": "16fcbf6a7b651cf7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 'apple', 9, 'banana', 7, 'cherry', 2, 'date', 5, 'elderberry', 'fig']\n",
      "[3, 'apple', 9, 7, 'cherry', 2, 'date', 5, 'elderberry', 'fig']\n",
      "[3, 'apple', 9, 7, 'cherry', 2, 'grape', 5, 'elderberry', 'fig']\n",
      "4\n",
      "3\n",
      "apple\n",
      "9\n",
      "7\n",
      "cherry\n",
      "2\n",
      "grape\n",
      "5\n",
      "elderberry\n",
      "fig\n",
      "[3, 'apple', 9, 7, 'cherry', 'kiwi', 2, 'grape', 5, 'elderberry', 'fig']\n",
      "9\n",
      "elderberry\n",
      "[9, 7, 'cherry', 'kiwi', 2]\n",
      "['fig', 'elderberry', 5, 'grape', 2, 'kiwi', 'cherry', 7, 9, 'apple', 3]\n",
      "[3, 'apple', 9, 7, 'cherry', 'kiwi', 2, 'grape', 5, 'elderberry', 'fig']\n",
      "[3, 'apple', 9, 7, 'cherry', 'elderberry', 2, 'fig', 5, 'grape', 'kiwi']\n",
      "['three', 'apple', 'nine', 'seven', 'cherry', 'elderberry', 'two', 'fig', 'five', 'grape', 'kiwi']\n"
     ]
    }
   ],
   "execution_count": 53
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T08:41:33.961666Z",
     "start_time": "2024-11-20T08:41:33.932666Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1. 创建一个列表包含从1到100的所有偶数。\n",
    "list2=[i for i in range(1,100+1) if i%2==0]\n",
    "print(list2)\n",
    "# 2. 将上述列表中所有偶数替换为它们的平方。\n",
    "list2=list(map(lambda x:x*x,list2))\n",
    "print(list2)\n",
    "# 3. 从上述列表中删除所有大于1000的数字。\n",
    "list2=[i for i in list2 if i<1000 ]\n",
    "print(list2)\n",
    "# 4. 将列表逆序。\n",
    "print(list2[::-1])\n",
    "# 5. 使用切片操作取出列表中的前10个元素。\n",
    "print(list2[:10])\n",
    "# 6. 将一个新列表`[101, 102, 103]`加到现有列表的末尾。\n",
    "list2.extend([101, 102, 103])\n",
    "print(list2)\n",
    "# 7. 计算列表中元素的平均值。\n",
    "print('{:.2f}'.format(sum(list2)/len(list2)))\n",
    "# 8. 找到列表中的最大值和最小值。\n",
    "print(max(list2))\n",
    "print(min(list2))\n",
    "# 9. 找出列表中第一次出现的11的索引位置。\n",
    "dict2=dict(enumerate(list2))\n",
    "for i,v in dict2.items():\n",
    "    if v==11:\n",
    "        print(i)\n",
    "else:\n",
    "    print(-1) # 没找到\n",
    "# 10. 用循环遍历列表，把每个数字替换为其对应的字符形式（例如：1替换为'1'）。注意使用不同类型的循环来实现。\n",
    "print(list(map(str,list2)))\n"
   ],
   "id": "2180e61d4b662e99",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]\n",
      "[4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304, 2500, 2704, 2916, 3136, 3364, 3600, 3844, 4096, 4356, 4624, 4900, 5184, 5476, 5776, 6084, 6400, 6724, 7056, 7396, 7744, 8100, 8464, 8836, 9216, 9604, 10000]\n",
      "[4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900]\n",
      "[900, 784, 676, 576, 484, 400, 324, 256, 196, 144, 100, 64, 36, 16, 4]\n",
      "[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]\n",
      "[4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 101, 102, 103]\n",
      "292.56\n",
      "900\n",
      "4\n",
      "-1\n",
      "['4', '16', '36', '64', '100', '144', '196', '256', '324', '400', '484', '576', '676', '784', '900', '101', '102', '103']\n"
     ]
    }
   ],
   "execution_count": 84
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T08:45:09.681084Z",
     "start_time": "2024-11-20T08:45:09.540709Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 11. 将列表中的所有元素转换成浮点数形式。\n",
    "print(list(map(float,list2)))\n",
    "# 12. 找出列表中所有大于50的元素个数。\n",
    "print([i for i in list2 if i>50])\n",
    "# 13. 在列表的第3个位置插入数字99。\n",
    "# list2.insert(2,99) # 哦，每执行一次代码块插一次99\n",
    "print(list2)\n",
    "# 14. 删除列表中的最后一个元素。\n",
    "print(list2.pop())\n",
    "print(list2)\n",
    "# 15. 使用列表推导式创建一个新列表，包含原列表中每个数字乘以2的结果。\n",
    "list3=[i*2 for i in list2 ]\n",
    "print(list3)\n",
    "print('-------------------------')\n",
    "# 16. 将列表分成两部分，一部分是小于等于50的数，另一部分是大于50的数。\n",
    "list3=[i for i in list2 if i<=50]\n",
    "list4=[i for i in list2 if i>50]\n",
    "print(list2)\n",
    "print(list3)\n",
    "print(list4)\n",
    "# 17. 将列表转换为一个字典，其中列表元素作为键，其在列表中的索引作为值。\n",
    "print(dict(zip(list2,range(len(list2))))) # zip()拉链函数到你上场了！\n",
    "# 18. 使用`enumerate`函数遍历列表，并打印元素及其索引。\n",
    "for i,v in enumerate(list2):\n",
    "    print(i,v)\n",
    "# 19. 从列表中随机取出一个元素。\n",
    "# 使用 random 模块中的 choice() 函数从列表中随机取出一个元素。\n",
    "import random\n",
    "print(random.choice(list2))\n",
    "# 20. 将列表保存到一个txt文件里，每个元素占一行。\n",
    "with open('list.txt','w') as file: # 打开文件写入\n",
    "    for i in list2:\n",
    "        file.write(str(i)+'\\n')"
   ],
   "id": "21c44171956966c5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[4.0, 16.0, 99.0, 36.0, 64.0, 100.0, 144.0, 196.0, 256.0, 324.0, 400.0, 484.0, 576.0, 676.0, 784.0, 900.0]\n",
      "[99, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900]\n",
      "[4, 16, 99, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900]\n",
      "900\n",
      "[4, 16, 99, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784]\n",
      "[8, 32, 198, 72, 128, 200, 288, 392, 512, 648, 800, 968, 1152, 1352, 1568]\n",
      "-------------------------\n",
      "[4, 16, 99, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784]\n",
      "[4, 16, 36]\n",
      "[99, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784]\n",
      "{4: 0, 16: 1, 99: 2, 36: 3, 64: 4, 100: 5, 144: 6, 196: 7, 256: 8, 324: 9, 400: 10, 484: 11, 576: 12, 676: 13, 784: 14}\n",
      "0 4\n",
      "1 16\n",
      "2 99\n",
      "3 36\n",
      "4 64\n",
      "5 100\n",
      "6 144\n",
      "7 196\n",
      "8 256\n",
      "9 324\n",
      "10 400\n",
      "11 484\n",
      "12 576\n",
      "13 676\n",
      "14 784\n",
      "576\n"
     ]
    }
   ],
   "execution_count": 88
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 字典练习题",
   "id": "5a61039b428b88c4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T08:58:25.024022Z",
     "start_time": "2024-11-20T08:58:24.921528Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 有一个字典`person_info` 储存了一个人的信息\n",
    "person_info = {\n",
    "    \"name\": \"Alex\",\n",
    "    \"age\": 30,\n",
    "    \"country\": \"USA\",\n",
    "    \"language\": [\"English\", \"Spanish\"],\n",
    "    \"is_student\": False\n",
    "}\n",
    "# 1.打印`person_info` 字典的`name` 值。\n",
    "print(person_info['name'])\n",
    "# 2.修改`age` 的值为 31。\n",
    "person_info['age']=31\n",
    "# 3.向字典中添加一个新的键值对 `height\": 175`。\n",
    "person_info['height']=175\n",
    "# 4.删除字典中的 `is_student\"` 键及其值。\n",
    "del person_info['is_student']\n",
    "# 5.使用循环遍历字典，打印所有的键和值。\n",
    "for k,v in person_info.items():\n",
    "    print(k,v)\n",
    "# 6.检查字典中是否有 `email\"` 这个键，如果没有，添加 `email\": \"alex@example.com\"`。\n",
    "person_info['email'] = \"alex@example.com\"\n",
    "# 7.将`language` 的值改为只包含 `English\"`。\n",
    "person_info['language']=[\"English\"]\n",
    "# 8.获取并打印字典中`language` 列表的长度。\n",
    "print(len(person_info['language']))\n",
    "# 9.向`language` 列表中添加一种新语言 `French\"`。\n",
    "person_info['language'].append(\"French\")\n",
    "# 10.循环插入新的键值对到字典：将 ` hobby'` + 数字 作为键，相应的 ` hobby'` + 数字值 作为值，数字从1至3。\n",
    "for i in range(1,4):\n",
    "    person_info[\"hobby'\"+str(i)]=\"hobby'\"+str(i)\n",
    "print(person_info)"
   ],
   "id": "e4b74308cbb878d7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Alex\n",
      "name Alex\n",
      "age 31\n",
      "country USA\n",
      "language ['English', 'Spanish']\n",
      "height 175\n",
      "1\n",
      "{'name': 'Alex', 'age': 31, 'country': 'USA', 'language': ['English', 'French'], 'height': 175, 'email': 'alex@example.com', \"hobby'1\": \"hobby'1\", \"hobby'2\": \"hobby'2\", \"hobby'3\": \"hobby'3\"}\n"
     ]
    }
   ],
   "execution_count": 89
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "您是一个数据分析师，现在您有一个包含公司员工个人信息的字典`employees`，其中每个键表示一个员工ID，对应的值是一个包含姓名、年龄、性别、职位、项目组和薪资历史列表的字典。\n",
    "\n",
    "员工信息的示例如下："
   ],
   "id": "c4898d9e1dc3b1cc"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-11-20T09:30:59.035044Z",
     "start_time": "2024-11-20T09:30:58.926067Z"
    }
   },
   "cell_type": "code",
   "source": [
    "employees = {  \n",
    "    101: {  \n",
    "        \"name\": \"Alice\",  \n",
    "        \"age\": 30,  \n",
    "        \"gender\": \"Female\",  \n",
    "        \"position\": \"Data Scientist\",  \n",
    "        \"team\": \"Research\",  \n",
    "        \"salary_history\": [70000, 80000, 90000]  \n",
    "         }\n",
    "}\n",
    "# 1. 新增一个员工的信息到`employees`字典中。\n",
    "one_info={ \"name\": \"kk\",  \n",
    "        \"age\": 26,  \n",
    "        \"gender\": \"Female\",  \n",
    "        \"position\": \"Java development\",  \n",
    "        \"team\": \"development\",  \n",
    "        \"salary_history\": [70000, 80000, 90000]  }\n",
    "employees[102]=one_info\n",
    "print(employees)\n",
    "# 2. 删除一个指定的员工的信息。\n",
    "del employees[102]\n",
    "# 3. 更新员工101的年龄至31。\n",
    "employees[101]['age']=31\n",
    "# 4. 增加员工101薪资历史中的最新薪资至95000。\n",
    "employees[101]['salary_history'].append(95000)\n",
    "print(employees)\n",
    "# 5. 计算员工101的平均薪资。\n",
    "print(sum(employees[101]['salary_history'])/len(employees[101]['salary_history']))\n",
    "# 6. 找出所有年龄大于25岁的员工的姓名和ID。\n",
    "for k,v in employees.items():\n",
    "    if employees[k]['age']>25:\n",
    "        print(k, employees[k]['name'])\n",
    "print('------------------')\n",
    "# 7. 对`employees`中的每个员工，添加'bonus'键至其字典中，其中值是最新薪资的10%。\n",
    "for k in employees.keys():\n",
    "    employees[k]['bonus']=employees[k]['salary_history'][-1]*0.1\n",
    "# 8. 将员工101的职位更新为\"Senior Data Scientist\"。\n",
    "employees[101]['position']=\"Senior Data Scientist\"\n",
    "# 9. 从员工的信息中移除`gender`键。\n",
    "for k in employees.keys():\n",
    "    if isinstance(employees[k],dict) and 'gender' in employees[k]:\n",
    "        del employees[k]['gender']\n",
    "# 10. 创建一个新的嵌套字典，该字典仅包含员工的`name`和`position`。\n",
    "two_info={'name':'cc','position':'python development'}\n",
    "employees[103]=two_info\n",
    "print(employees)"
   ],
   "id": "cc10bb5660b295b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{101: {'name': 'Alice', 'age': 30, 'gender': 'Female', 'position': 'Data Scientist', 'team': 'Research', 'salary_history': [70000, 80000, 90000]}, 102: {'name': 'kk', 'age': 26, 'gender': 'Female', 'position': 'Java development', 'team': 'development', 'salary_history': [70000, 80000, 90000]}}\n",
      "{101: {'name': 'Alice', 'age': 31, 'gender': 'Female', 'position': 'Data Scientist', 'team': 'Research', 'salary_history': [70000, 80000, 90000, 95000]}}\n",
      "83750.0\n",
      "101 Alice\n",
      "------------------\n",
      "{101: {'name': 'Alice', 'age': 31, 'position': 'Senior Data Scientist', 'team': 'Research', 'salary_history': [70000, 80000, 90000, 95000], 'bonus': 9500.0}, 103: {'name': 'cc', 'position': 'python development'}}\n"
     ]
    }
   ],
   "execution_count": 101
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "**主要的函数**\n",
    "- count()\n",
    "- find()\n",
    "- index()\n",
    "- replace()\n",
    "- split()\n",
    "- join()\n",
    "- reversed()\n",
    "- isnumeric()\n",
    "- capitalize()\n",
    "- sorted()\n",
    "---\n",
    "- enumerate()\n",
    "- map()\n",
    "- lambda\n",
    "- zip()\n",
    "- isinstance()\n",
    "- re(正则表达式)\n",
    "- 列表生成式"
   ],
   "id": "cc4b7c52cdbfdfcd"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "1bc0184992eb482f"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
